// pages/search/index.js
import * as request from "../../utils/request/file/file.js"
import * as request1 from "../../utils/request/file/favourFile.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    value: "",
    loadingMore: false,
    loading: false,
    value: '',
    file: [],
    current: 1,
    pageSize: 6,
    loadText: '加载中...',
    tatol: 0,
    hasMore: true,
    fileOptions: [
      '标题',
      "内容",
      "分类"
    ],
    index: 0,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },
  onClick(params) {
    this.setData({
      pageIndex: 1,
      file: []
    })

    this.getfileInfo()
  },
  onChange(e) {
    this.setData({
      value: e.detail
    })
  },
  onReachBottom: function () {

    if (!this.data.hasMore) {
      this.setData({
        loadingMore: true,
        loadText: "没有更多了"
      });
      setTimeout(() => {
        this.setData({
          loadingMore: false,
        });
      }, 800)
      return;
    }
    this.setData({
      loadingMore: true,
      loadText: "加载更多..."
    });
    let current = this.data.current + 1
    this.setData({
      current: current
    })
    this.getfileInfo()
  },
  preventDefault: function (e) {
    // 阻止触摸事件的默认行为，防止滚动  
    console.log(e)
    e.stopPropagation();
    e.preventDefault();
  },
  async openDOCX(event) {
    // wx.navigateTo({
    //   url: `/pages/index/article?id=${param}`,
    // })
    let self = this
    this.setData({
      loading: true
    })
    const param = event.currentTarget.dataset.param
    const fs = wx.getFileSystemManager()
    wx.getStorage({
      key: `file${param}`,
      success(res) {
        wx.openDocument({
          filePath: res.data.path,
          fileType: res.data.type, // 根据文件类型设置
          success: function (res) {
            self.setData({
              loading: false
            })
            //console.log('文档打开成功',res);
          },
          fail: function (err) {
            console.error('文档打开失败', err);
            wx.showToast({
              title: '文档打开失败',
            })
          }
        });
      },
      async fail() {
        let session = wx.getStorageSync('session')
        console.log(param)
        try {
          let res = await request.queryFile({
            id: param
          }, session)
          console.log(res)
          let info = res.data.records[0]
          let filePath = info.fileIlk == "" ? wx.env.USER_DATA_PATH + `/${info.name}.docx` : wx.env.USER_DATA_PATH + `/${info.name}.${info.fileIlk}`
          console.log(filePath)
          fs.writeFile({
            filePath: filePath,
            data: wx.base64ToArrayBuffer(res.data.records[0].content), // 确保这是正确的二进制数据或编码后的字符串  
            encoding: "binary",
            success: function (writeRes) {
              console.log("成功写入文件", writeRes);
              wx.setStorageSync(`file${res.data.records[0].id}`, {
                path: filePath,
                type: res.data.records[0].fileIlk
              })
              wx.openDocument({
                filePath: filePath,
                fileType: res.data.records[0].fileIlk, // 根据文件类型设置
                success: function (res) {
                  self.setData({
                    loading: false
                  })
                  //console.log('文档打开成功',res);
                },
                fail: function (err) {
                  console.error('文档打开失败', err);
                  wx.showToast({
                    title: '文档打开失败',
                  })
                }
              });
            },
            fail: function (err) {
              //console.error("写入文件失败", err);  
            }
          })
        } catch (err) {
          self.setData({
            loading: false
          })
          wx.showToast({
            title: '文档打开失败',
            icon: "none"
          })
        }
      }
    })

  },
  async onLoad(options) {
    let session = wx.getStorageSync('session')
    let res = await request.queryFile({
      id: 1
    }, session)
    this.setData({
      tatol: res.data.size
    })
  },
  async getfileInfo(isFavour) {
    this.setData({
      loadingMore: true,
      loadText: "加载更多..."
    });
    let session = wx.getStorageSync('session')

    //let strat = (this.data.current - 1) * this.data.pageSize
    let pageSize = this.data.pageSize
    console.log(pageSize)
    let res, data;
    if (isFavour) {
      res = await request.listFilePro({
        current: 1,
        pageSize: this.data.file.length,
        name:this.data.value
      }, session)
      this.setData({
        file: res.data.records
      })
      console.log(this.data.file)
      this.setData({
        loadingMore: false,
        loadText: ""
      });
      return
    }
    data = {
      current: this.data.current,
      pageSize: pageSize
    }
    console.log(this.data.index)
    data.name = this.data.value
    res = await request.listFilePro(data, session)
    console.log(data)
    console.log(res)
    let arr = []
    arr = JSON.parse(JSON.stringify(this.data.file))
    //console.log(this.data.file)
    if (res.code == 0) {
      for (const item of res.data.records) {
        arr.push(item)
      }
      this.setData({
        file: arr
      })
      console.log(res.data.total, this.data.file)

      this.setData({
        loadingMore: false,
        hasMore: res.data.total > this.data.file.length,
      });
    } else {
      this.setData({
        loadText: "加载失败"
      });
      setTimeout(() => {
        this.setData({
          loadingMore: false
        });
      }, 300)
    }
  },
  async handleFavour(event) {
    const param = event.currentTarget.dataset.param
    let session = wx.getStorageSync('session')
    console.log(param)
    let res = await request1.favourFile({
      fileId: param
    }, session)
    console.log(res)
    if (res.code === 0) {
      if (res.data == 1) {
        this.getfileInfo(true)

        wx.showToast({
          title: "收藏成功",
        })
      } else {
        wx.showToast({
          title: '取消收藏成功',
          icon: "none"
        })
      }
    } else {
      wx.showToast({
        title: '收藏失败',
        icon: "none"
      })
    }

  },
  // bindPickerChange: function (e) {
  //   this.setData({
  //     index: e.detail.value,
  //     selected: this.data.fileOptions[e.detail.value]
  //   });

  // }
})